/**
 * @p.md
 * 
 * 示例执行入口
 */

import * as readline from 'readline';

// 示例列表
const examples = [
  {
    name: 'Persistent Counter (In-Memory & FileSystem)',
    module: './persistent-counter-example'
  },
  {
    name: 'Persistent Counter (SQLite)',
    module: './persistent-sqlite-example'
  },
  {
    name: 'Persistent Counter (MongoDB)',
    module: './persistent-mongodb-example'
  },
  {
    name: 'Persistent Counter (PostgreSQL)',
    module: './persistent-postgresql-example'
  }
];

/**
 * 创建交互式命令行接口
 */
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

/**
 * 显示示例列表
 */
function showExamples() {
  console.log('\n选择要运行的示例:');
  examples.forEach((example, index) => {
    console.log(`${index + 1}. ${example.name}`);
  });
  console.log('0. 退出');
}

/**
 * 运行示例
 * @param index 示例索引
 */
async function runExample(index: number) {
  if (index === 0) {
    rl.close();
    return;
  }

  if (index < 1 || index > examples.length) {
    console.log('无效的选择，请重新选择');
    showExamples();
    return;
  }

  const example = examples[index - 1];
  console.log(`\n运行示例: ${example.name}`);
  
  try {
    // 动态导入并运行示例
    const module = await import(example.module);
    if (typeof module.runExample === 'function') {
      await module.runExample();
    } else {
      console.log('示例没有导出 runExample 函数');
    }
  } catch (error) {
    console.error('运行示例时出错:', error);
  }

  // 运行完毕后显示菜单
  console.log('\n示例运行完毕');
  showExamples();
}

/**
 * 开始交互式菜单
 */
function startMenu() {
  showExamples();

  rl.on('line', (input) => {
    const choice = parseInt(input.trim(), 10);
    runExample(choice);
  });

  rl.on('close', () => {
    console.log('再见!');
    process.exit(0);
  });
}

// 启动交互式菜单
startMenu(); 